package com.gameGroups.Controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.gameGroups.Service.ImgUploadService;
import com.gameGroups.Utils.GetRandomNum;
import com.gameGroups.Utils.MyException;


@Controller
@RequestMapping("/upload")
public class ImgUploadController {
	@Autowired
	private ImgUploadService imgUploadService;

	  //头像图片上传
	  @RequestMapping(value="/headImg.do")
	  @ResponseBody
	  public Map<String,Object> userHeadImg(@RequestParam(value="headImg") CommonsMultipartFile files[],HttpServletRequest request,HttpServletResponse response) throws MyException{
		  Map<String,Object> model=new HashMap<String, Object>();
		  try {
			  String uid = request.getParameter("uid");
			  String basePath=System.getProperty("basePath");
			  String headImg = uploadUserImgUtil(files,basePath,uid);
			  model.put("uid", uid);
			  model.put("headImg", headImg);
			  imgUploadService.updateUserImg(model);
			  imgUploadService.updateWorksHeadImg(model);
			  imgUploadService.updateWorksExtHeadImg(model);
			  model.put("status", "0000");
		} catch (Exception e) {
			  model.put("status", "9999");
			  model.put("errorMessage", "系统异常!");
			  throw new MyException("头像图片上传功能异常!"+":"+e);
		}
		  return model;
	  }
	  
	  //背景图片上传
	  @RequestMapping(value="/topImg.do")
	  @ResponseBody
	  public Map<String,Object> userTopImg(@RequestParam(value="topImg") CommonsMultipartFile files[],HttpServletRequest request,HttpServletResponse response) throws MyException{
		  Map<String,Object> model=new HashMap<String, Object>();
		  try {
			  String uid = request.getParameter("uid");
			  String basePath=System.getProperty("basePath");
			  String topImg = uploadUserImgUtil(files,basePath,uid);
			  model.put("uid", uid);	
			  model.put("topImg", topImg);
		      imgUploadService.updateUserImg(model);
			  model.put("status", "0000");	
		} catch (Exception e) {
			  model.put("status", "9999");
			  model.put("errorMessage", "系统异常!");
			  throw new MyException("背景图片上传功能异常!"+":"+e);
		}
	      return model;
	  } 
	
	  
	  //xia
	  @RequestMapping(value="/download.do",method=RequestMethod.GET)
	  public void downloadAkp(HttpServletRequest request,HttpServletResponse response) throws FileNotFoundException{
		  // path是指欲下载的文件的路径。
	      File file = new File("/usr/App.apk");
	      // 读到流中
	      InputStream inStream = new FileInputStream(file);// 文件的存放路径
	      // 设置输出的格式
	      response.reset();
	      response.setContentType("bin");
	      // 设置response的Header
	      response.addHeader("Content-Disposition", "attachment;filename=doubaoApp.apk");
	      response.addHeader("Content-Length", "" + file.length());
	      // 循环取出流中的数据
	      byte[] b = new byte[1024];
	      int len;
	      try {
	          while ((len = inStream.read(b)) > 0)
	          response.getOutputStream().write(b, 0, len);
	          inStream.close();
	      } catch (IOException e) {
	          e.printStackTrace();
	      }
	  }
	  
	  
	  //上传图片工具类
	  private String uploadUserImgUtil(CommonsMultipartFile files[], String basePath, String file){
		  
	        StringBuffer worksImg=new StringBuffer();
	    	  if (files.length>0) {
	        	String path =basePath+file;
	        	for (int i = 0; i < files.length; i++) {
	        		if (!files[i].isEmpty()) {
	        			String fileName = files[i].getOriginalFilename();
	        			String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());//获取文件后缀名
	        			fileName=GetRandomNum.getNum(10)+fileSuffix;
	        			String worksUrl=file+"/"+fileName;
	        			if (i==0) {
	        				worksImg.append(worksUrl);
	  				    }else{
	  					    worksImg.append(","+worksUrl);
	  				    }
	                	File targetFlie=new File(path,fileName);
	                	if (!targetFlie.exists()) {
	                		targetFlie.mkdirs();
	        			}
	                	try {
	                	  files[i].transferTo(targetFlie);
	        			} catch (Exception e) {
	        	           e.printStackTrace();
	        			}	
	  				}				
	  			} 
	  		} 
	    	return worksImg.toString();
	    }
}
